<?php

declare(strict_types=1);
/*
 * This file is part of Leonsw.
 *
 * @link     https://leonsw.com
 * @document https://docs.leonsw.com
 * @contact  leonsw.com@gmail.com
 * @license  https://leonsw.com/LICENSE
 */

namespace App\Repositories\Lottery;


use App\Exceptions\BasicException;
use App\Models\MainDB\Lottery\CompensatePool as Model;

use App\Traits\Singleton;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Support\Facades\DB;

class CompensatePoolRepository
{
    use Singleton;

    public function get()
    {
        $query = Model::query();
        return $query->get();
    }

    public function drawSingle()
    {
        $drawCount  = 1; // 固定抽取次数为1
        $prizes     = Collection::make([]);
        $poolPrizes = $this->checkDraw($drawCount)->each(function ($item) use (&$prizes) {
            $prizeCount = $item->count;
            while ($prizeCount) {
                $prizes = $prizes->push($item->prize_id);
                $prizeCount--;
            }
        });
        $prizeId    = $prizes->shuffle()->random(); // 随机奖品
        $id         = $poolPrizes->where('prize_id', $prizeId)->first()->id;
        $this->update($id, [
            "count"      => DB::raw("`count` - $drawCount"),
            "draw_count" => DB::raw("`draw_count` + $drawCount"),
        ]);
        return ['prize_id' => $prizeId];
    }

    public function checkDraw(int $drawCount)
    {
        $prizes      = $this->get();
        $prizesCount = $prizes->sum('count');
        if ($prizesCount < $drawCount) {
            if ($prizes->sum('template_count') <= 0) {
                throw new BasicException(-1, '用户抽奖异常');
            }
            foreach ($prizes as $prize) {
                $prize->count += $prize->template_count;
                $prize->save();
            }
        }
        return $prizes;
    }

    public function one(array $filters, bool $fail = false)
    {
        $query = Model::query();
        $query->where($filters);
        return $fail ? $query->firstOrFail() : $query->first();
    }

    public function find(int $id)
    {
        return $this->one(['id' => $id], true);
    }

    public function create(array $data)
    {
        $model = new Model();
        $model->fill($data);
        $model->save();
        $model->refresh();
        return $model;
    }

    public function update(int $id, array $data)
    {
        $query = Model::query();
        $query->where('id', $id);
        return $query->update($data);
    }
}
